package com.fulu.javabase.arithmetic.array;

import java.util.Arrays;

/**
 * Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
 *
 * Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
 *
 * Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
 * Return k.
 * https://leetcode.cn/problems/remove-element/
 */
public class RemoveElement {

    // 暴力双循环省略

    /**
     * 相向双指针
     * @param nums
     * @param val
     * @return
     */
    public static int removeElement(int[] nums, int val){
        int left = 0;
        int right = nums.length - 1;
        while(left <= right){
            if(nums[left] == val){
                nums[left] = nums[right];
                right--;
            }else {
                left++;
            }
        }
        return left;
    }

    /**
     * 快慢双指针
     * @param nums
     * @param val
     * @return
     */
    public static int removeElement1(int[] nums, int val){
        int slow = 0;
        int fast = 0;
        while(fast < nums.length){
            if(fast > slow){
                nums[slow] = nums[fast];
            }
            if(nums[slow] != val){
                slow++;
            }
            fast++;
        }
        return slow;
    }

    public static void main(String[] args) {
        int[] nums = {1}; // Input array
        int val = 1; // Value to remove

        int k = removeElement1(nums, val); // Calls your implementation
        System.out.println(k);
        System.out.println(Arrays.toString(nums));
    }
}
